package 哈希表系列;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class IsHappy {

    private int getNextNum(int n){
        int res = 0;
        while (n > 0){
            int temp = n % 10;  //存储当前位的数字
            res += temp * temp; //求和
            n = n / 10;         //下一位
        }
        return res;
    }

    //方法一：用哈希集合检测循环
//    public boolean isHappy(int n) {
//        Set<Integer> record = new HashSet<>();
//        while (n != 1 && !record.contains(n)){
//            record.add(n);
//            n = getNextNum(n);
//        }
//        return n == 1;
//    }

    //快慢指针法
//    public boolean isHappy(int n) {
//        int slowRunner = n;
//        int fastRunner = getNextNum(n);
//        while (fastRunner != 1 && slowRunner != fastRunner) {
//            slowRunner = getNextNum(slowRunner);
//            fastRunner = getNextNum(getNextNum(fastRunner));
//        }
//        return fastRunner == 1;
//    }

    //数学法
    private static Set<Integer> cycleMembers =
            new HashSet<>(Arrays.asList(4, 16, 37, 58, 89, 145, 42, 20));

    public boolean isHappy(int n) {
        while (n != 1 && !cycleMembers.contains(n)) {
            n = getNextNum(n);
        }
        return n == 1;
    }


}
